﻿/***************************************************************************/
/// <summary>
/// 
///  <title>SLIC ImageController</title>
///  <description>ImageController for Image Upload action</description>
///  <copyRight>Copyright (c) 2010</copyRight>
///  <company>IronOne Technologies (Pvt)Ltd</company>
///  <createdOn>2011-08-01</createdOn>
///  <author>Rajith (Intern)</author>
///  <modification>
///     <modifiedBy></modifiedBy>
///      <modifiedDate></modifiedDate>
///     <description></description>
///  </modification>
///
/// </summary>
/***************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using System.Xml;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;

#region SLICRef
using SLIC.Models.EntityModel;
using SLIC.Models.Enums;
using SLIC.HandlerClasses;
#endregion SLICRef

#region ThirdPartyRef
using log4net;
#endregion ThirdPartyRef

namespace SLIC.Controllers
{
    public class ImageController : BaseController
    {
        protected static readonly ILog log = LogManager.GetLogger("root");
        //
        // GET: /Image/

        public ActionResult Index()
        {
            return View();
        }

        #region xml action
        /*
        ///ImageUpload Action Method        
        ///<returns>
        /// to ImageUploadView
        ///</returns>       
        ///<exception cref="">
        ///JobNo not found
        ///Please upload a file.
        ///image name cant be empty
        ///Field cant be empty
        ///Please upload a Image
        ///Error occurred while connecting to the database.Please try again later
        /// </exception>
        /// <remarks>this method uploads the images to a folder and save those data in database table</remarks>
        public virtual ActionResult UploadImage()
        {
            XmlDocument xmlDoc = null;
            HttpPostedFileBase imageFile = null;
            bool isReSubmission = false;
            int refNo = 0;

            //log.Info("this is a test log entry");
            log.Info(LogPoint.Entry.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name);
            try
            {
                if (Request.Files.Count != 2)
                {
                    throw new GenException(701, "Upload does not contains two files");
                }
                foreach (string file in Request.Files)
                {
                    var file1 = Request.Files[file] as HttpPostedFileBase;

                    if (file.Equals("ImageData"))
                    {
                        //  string tempXMLSaveLocation = ConfigurationManager.AppSettings["ImageSavePath"].ToString() + "TempXML_" + String.Format("{0:MM_dd_yyyy_HH-mm-ss}", DateTime.Now);
                        //  StaticMethods.CreateFolder(tempXMLSaveLocation);

                        //  file1.SaveAs(tempXMLSaveLocation + "\\" + Path.GetFileName(file1.FileName));
                        //  XmlTextReader reader = new XmlTextReader(tempXMLSaveLocation + "\\" + Path.GetFileName(file1.FileName));
                        XmlTextReader reader = new XmlTextReader(file1.InputStream);
                        reader.WhitespaceHandling = WhitespaceHandling.None;
                        xmlDoc = new XmlDocument();
                        //Load the file into the XmlDocument
                        xmlDoc.Load(reader);
                        //Close off the connection to the file.
                        reader.Close();
                        //StreamReader reader = new StreamReader(file1.InputStream);
                        //xmlDoc = new XmlDocument();
                        //xmlDoc.LoadXml(reader.ReadToEnd());

                    }
                    else if (file.Equals("Image"))
                    {
                        imageFile = Request.Files[file] as HttpPostedFileBase;
                    }
                }

                using (SLICEntities slicImg = DataObjectFactory.CreateContext())
                {
                    if (xmlDoc == null)
                    {
                        throw new GenException(707, "Request does not contain an xml file.");
                    }

                    XmlNode imgNode = xmlDoc.SelectSingleNode("Request/Data/Image/FieldList");
                    string jobNo = imgNode.SelectSingleNode("jobNo").InnerText;//"j1001";                  
                    string imageName = imgNode.SelectSingleNode("imageName").InnerText;//"Stonehenge";
                    string field = imgNode.SelectSingleNode("fieldId").InnerText;//3-"AccidentImages";

                    XmlNode submissionNode = imgNode.SelectSingleNode("isResubmission");

                    try
                    {                     

                        //remove logging
                        if (submissionNode != null && bool.Parse(submissionNode.InnerText))
                        {
                            isReSubmission = true;
                            try
                            {
                                refNo = int.Parse(imgNode.SelectSingleNode("refNo").InnerText);
                            }
                            catch (Exception)
                            {
                                throw new GenException(808, "Invalid image reference no.");
                            }
                        }
                        else
                        {
                            isReSubmission = false;
                        }
                    }
                    catch (Exception e)
                    {
                        //error in converting string to Boolean
                        log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + e.Message);
                    }

                    if (imageFile.ContentLength == 0)
                    {
                        throw new GenException(702, "Please upload an image.");
                    }
                    if (string.IsNullOrEmpty(imageName))
                    {
                        throw new GenException(703, "Image name cant be empty");
                    }
                    if (string.IsNullOrEmpty(jobNo))
                    {
                        throw new GenException(707, "Job No cannot be empty.");
                    }
                    jobNo = jobNo.Trim();
                    if (string.IsNullOrEmpty(field))
                    {
                        throw new GenException(704, "Field cant be empty");
                    }
                    byte fieldID;
                    if (!Byte.TryParse(field, out fieldID))
                    {
                        throw new GenException(705, "Field should be a byte value");
                    }
                    //fieldID = byte.Parse(field);
                    //if (model.DocID == 0)
                    //{
                    //on add
                    // byte fieldID = (byte)Enum.Parse(typeof(FieldName), field, true);
                    string fieldName = Enum.GetName(typeof(FieldName), fieldID);
                    if (string.IsNullOrEmpty(fieldName))
                    {
                        throw new GenException(706, "Error in Finding FieldName");
                    }

                    //   3;// (byte)Enum.Parse(typeof(FieldName), Enum.GetName(typeof(FieldName), field));
                    Job job = (from j in slicImg.Jobs where j.JobNo == jobNo select j).FirstOrDefault();

                    if (job == null)
                    {
                        throw new GenException(707, "Job Number not found");
                    }
                    //if (file1.ContentType != "application/pdf")
                    //{
                    //    throw new GenException(202, "Only .pdf files are allowed.");
                    //}
                    string commonFolderPath = "ImageGallery\\" + jobNo + "\\" + fieldName;

                    if (isReSubmission && refNo != 0)
                    {
                        commonFolderPath = "ImageGallery\\" + jobNo + "\\Visit_" + refNo + "\\" + fieldName;
                    }

                    //   string filePath = ConfigurationManager.AppSettings["ImageSavePath"].ToString() + "ImageGallery\\" + jobNo + "\\" + fieldName;
                    string filePath = ConfigurationManager.AppSettings["ImageSavePath"].ToString() + commonFolderPath;
                    if (string.IsNullOrEmpty(filePath))
                    {
                        throw new GenException(708, "Error in Retrieving a path to save");
                    }
                    //Server.MapPath(filePath);
                    FolderCreater.CreateFolder(filePath);
                    log.Info(LogPoint.Success.ToString() + ",Folders created at:" + filePath);

                    DateTime now = DateTime.Now;

                    string dateTimeStamp = String.Format("{0:MM_dd_yyyy_HH-mm-ss}", now);


                    // FileStream     
                   
                    string newImageName = jobNo + "_" + dateTimeStamp + "_" + fieldName + "_" + Path.GetFileName(imageFile.FileName);
                    string pathforDB = commonFolderPath + "\\" + newImageName;

                    string fileSavePath = ConfigurationManager.AppSettings["ImageSavePath"].ToString() + pathforDB;

                    //string pathforDB = "ImageGallery\\" + jobNo + "\\" + fieldName + "\\" + dateTimeStamp + "_" + Path.GetFileName(imageFile.FileName);
                    if (System.IO.File.Exists(fileSavePath))
                    {
                        throw new GenException(709, "Image Already exists");
                    }

                    imageFile.SaveAs(fileSavePath);

                    //logged on sucess of file upload 
                    log.Info(LogPoint.FileUploaded.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + jobNo + User.Identity.Name + ",File Name:" + fileSavePath);

                    ImageGallery uploadedImg = new ImageGallery();
                    uploadedImg.JobId = int.Parse(job.Id.ToString());
                    uploadedImg.FieldId = fieldID;
                    // uploadedImg.ImageName = imageName;
                    uploadedImg.ImageName = newImageName;
                    //uploadedImg.ImagePath = fileSavePath;
                    uploadedImg.ImagePath = pathforDB;
                    uploadedImg.Title = fieldName + " | " + imageName;
                    //lush
                    uploadedImg.IsPrinted = false;
                    uploadedImg.UploadedDate = DateTime.Now;
                    uploadedImg.IsReSubmission = isReSubmission;

                    //uploadedImg.User = ;

                    //uploadedImg.Info = "This is a image saved for " + fieldName + " as " + imageName;

                    //slicImg.ImageGalleries.get
                    imageFile.SaveAs(fileSavePath);

                    slicImg.AddToImageGalleries(uploadedImg);
                    slicImg.SaveChanges();
                    //log.Info("Image entity saved. Image Id: " + uploadedImg.ImageId);
                    //For Resubmissions                
                    ViewData["ImageId"] = uploadedImg.ImageId;
                    log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Add image details to image gallery," + User.Identity.Name + ",[Params=(Job Id:" + uploadedImg.JobId + ", Field Id:" + uploadedImg.FieldId + ", Image Name:" + uploadedImg.ImageName + ")]");

                    //Check whether to send email     

                    short? imageCount = job.ImageCount;

                    // log.Info("Ref No:" + refNo + ",ImageCount of Job:" + imageCount);

                    JobController jobCont = new JobController();

                    if (!isReSubmission && imageCount != null && job.ImageGalleries != null && (job.ImageGalleries.Count == imageCount))
                    {
                        // log.Info("Inside not is resubmission!");
                        //Send email            
                        try
                        {
                            jobCont.SendJobEmail(job, true);
                            log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + "Email sending started");
                            //  log.Info("Email send success for images.");
                        }
                        catch (Exception e)
                        {
                            log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image - Send Email," + User.Identity.Name + "," + e.Message);
                            // log.Info("Email send failure for images.");
                        }

                    }
                    else if (isReSubmission && refNo != 0)
                    {
                        // log.Info("Inside is resubmission!");
                        Job_ReSubmissions submission = (from s in slicImg.Job_ReSubmissions
                                                        where s.RefNo == refNo
                                                        select s).FirstOrDefault();

                        imageCount = submission.ImageCount;
                        //   log.Info("Ref No:" + refNo + ",ImageCount of Submission:" + imageCount);
                        if (submission != null)
                        {
                            //  log.Info("Submission Entity not null");
                            submission.ImageGalleries.Add(uploadedImg);
                            slicImg.SaveChanges();
                            // log.Info("Saved to link table on submission.");

                            if (imageCount != null && submission.ImageGalleries != null && (submission.ImageGalleries.Count == imageCount))
                            {
                                try
                                {
                                    jobCont.SendReSubmissionEmail(submission, true);
                                    log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + "Email sending started");
                                    // log.Info("Email send success for images on resubmission.");
                                }
                                catch (Exception e)
                                {
                                    log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image - Send Email," + User.Identity.Name + "," + e.Message);
                                    // log.Info("Email send failure for images on resubmission.");
                                }

                            }
                        }
                        else
                        {
                            //Submission entity not found for the image                           
                            throw new GenException(807, "Image ReSubmission entity not found.");
                        }
                    }
                    //logged on Success
                    log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image overall," + User.Identity.Name);
                }
            }
            catch (ArgumentException e)
            {
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + e.Message);
                ModelState.AddModelError("err", new GenException(710, "Error in handling ENUM"));
            }
            catch (GenException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + ex.Message);
                ModelState.AddModelError("err", ex);
            }
            catch (XmlException e)
            {
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + e.Message);
                ModelState.AddModelError("err", new GenException(711, "Error in xml data"));
            }
            catch (IOException e)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + e.Message);
                ModelState.AddModelError("err", new GenException(712, "File Path not Accessible"));
            }
            catch (EntityException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + ex.Message);
                ModelState.AddModelError("err", new GenException(713, "Error occurred while connecting to the database.Please try again later"));
            }
            catch (Exception e)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + e.Message);
                ModelState.AddModelError("err", new GenException(714, e.ToString()));
            }

            return GetFormatView("Image/ImageUpload.aspx");
        }
        */

        ///ImageUpload Action Method        
        ///<returns>
        /// to ImageUploadView
        ///</returns>       
        ///<exception cref="">
        ///JobNo not found
        ///Please upload a file.
        ///image name cant be empty
        ///Field cant be empty
        ///Please upload a Image
        ///Error occurred while connecting to the database.Please try again later
        /// </exception>
        /// <remarks>this method uploads the images to a folder and save those data in database table</remarks>
        public virtual ActionResult UploadImage()
        {
            XmlDocument xmlDoc = null;
            HttpPostedFileBase imageFile = null;
            bool isReSubmission = false;
            int refNo = 0;

            try
            {
                log.Info(LogPoint.Entry.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name);

                if (Request.Files.Count != 2)
                {
                    throw new GenException(701, "Upload does not contains two files");
                }
                //Fetch and process Request Files
                foreach (string file in Request.Files)
                {
                    var imageXmlFile = Request.Files[file] as HttpPostedFileBase;

                    if (file.Equals("ImageData"))
                    {
                        XmlTextReader reader = new XmlTextReader(imageXmlFile.InputStream);
                        reader.WhitespaceHandling = WhitespaceHandling.None;
                        try
                        {
                            xmlDoc = new XmlDocument();
                            xmlDoc.Load(reader);
                        }
                        catch (Exception)
                        {
                            throw new GenException(777, "Error in reading image xml.");
                        }
                        //Close off the connection to the file.
                        reader.Close();
                    }
                    else if (file.Equals("Image"))
                    {
                        imageFile = Request.Files[file] as HttpPostedFileBase;
                    }
                }

                if (xmlDoc == null)
                {
                    throw new GenException(707, "Request does not contain an xml file.");
                }
                //Process XML File
                XmlNode imgNode = xmlDoc.SelectSingleNode("Request/Data/Image/FieldList");
                string jobNo = imgNode.SelectSingleNode("jobNo").InnerText;//"j1001";                  
                string imageName = imgNode.SelectSingleNode("imageName").InnerText;//"Stonehenge";
                string field = imgNode.SelectSingleNode("fieldId").InnerText;//3-"AccidentImages";
                XmlNode submissionNode = imgNode.SelectSingleNode("isResubmission");

                try
                {
                    if (submissionNode != null && bool.Parse(submissionNode.InnerText))
                    {
                        isReSubmission = true;
                        try
                        {
                            refNo = int.Parse(imgNode.SelectSingleNode("refNo").InnerText);
                        }
                        catch (Exception)
                        {
                            throw new GenException(808, "Invalid image reference no.");
                        }
                    }
                    else
                    {
                        isReSubmission = false;
                    }
                }
                catch (Exception e)
                {
                    //error in converting string to Boolean
                    log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + e.Message);
                }

                //Process Image File
                if (imageFile.ContentLength == 0)
                {
                    throw new GenException(702, "Please upload an image.");
                }
                if (string.IsNullOrEmpty(imageName))
                {
                    throw new GenException(703, "Image name cant be empty");
                }
                if (string.IsNullOrEmpty(jobNo))
                {
                    throw new GenException(707, "Job No cannot be empty.");
                }

                jobNo = jobNo.Trim();

                if (string.IsNullOrEmpty(field))
                {
                    throw new GenException(704, "Field cant be empty");
                }
                byte fieldID;
                if (!Byte.TryParse(field, out fieldID))
                {
                    throw new GenException(705, "Field should be a byte value");
                }
                //process field id enum
                string fieldName = Enum.GetName(typeof(FieldName), fieldID);
                if (string.IsNullOrEmpty(fieldName))
                {
                    throw new GenException(706, "Error in Finding FieldName");
                }

                using (SLICEntities slicImg = DataObjectFactory.CreateContext())
                {
                    Job job = (from j in slicImg.Jobs where j.JobNo == jobNo select j).FirstOrDefault();

                    if (job == null)
                    {
                        throw new GenException(707, "Job not found");
                    }

                   // string imagepath = this.SaveImage(imageFile, jobNo, fieldName, isReSubmission, refNo);
                    /*
                     string commonFolderPath = "ImageGallery\\" + jobNo + "\\" + fieldName;

                     if (isReSubmission && refNo != 0)
                     {
                         commonFolderPath = "ImageGallery\\" + jobNo + "\\Visit_" + refNo + "\\" + fieldName;
                     }

                     string filePath = ConfigurationManager.AppSettings["ImageSavePath"].ToString() + commonFolderPath;
                     if (string.IsNullOrEmpty(filePath))
                     {
                         throw new GenException(708, "Error in Retrieving a path to save");
                     }

                     FolderCreater.CreateFolder(filePath);
                     log.Info(LogPoint.Success.ToString() + ",Folders created at:" + filePath);

                     DateTime now = DateTime.Now;

                     string dateTimeStamp = String.Format("{0:MM_dd_yyyy_HH-mm-ss}", now);


                     string newImageName = jobNo + "_" + dateTimeStamp + "_" + fieldName + "_" + Path.GetFileName(imageFile.FileName);
                     string pathforDB = commonFolderPath + "\\" + newImageName;

                     string fileSavePath = ConfigurationManager.AppSettings["ImageSavePath"].ToString() + pathforDB;

                     if (System.IO.File.Exists(fileSavePath))
                     {
                         throw new GenException(709, "Image Already exists");
                     }

                     imageFile.SaveAs(fileSavePath);

                     //logged on sucess of file upload 
                     log.Info(LogPoint.FileUploaded.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + jobNo + User.Identity.Name + ",File Name:" + fileSavePath);
                     */

                    #region AddImageEntityToDB
                    ImageGallery uploadedImg = this.SaveImage(imageFile, jobNo, fieldName, isReSubmission, refNo);
                    uploadedImg.JobId = int.Parse(job.Id.ToString());
                    uploadedImg.FieldId = fieldID;
                   // uploadedImg.Title = fieldName + " | " + imageName;
                    uploadedImg.IsPrinted = false;
                    uploadedImg.UploadedDate = DateTime.Now;
                    uploadedImg.IsReSubmission = isReSubmission;
                 
                   // imageFile.SaveAs(fileSavePath);

                    slicImg.AddToImageGalleries(uploadedImg);
                    slicImg.SaveChanges();
                    //log.Info("Image entity saved. Image Id: " + uploadedImg.ImageId);
                    
                    #endregion AddImageEntityToDB

                    //For Resubmissions                
                    ViewData["ImageId"] = uploadedImg.ImageId;
                    log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Add image details to image gallery," + User.Identity.Name + ",[Params=(Job Id:" + uploadedImg.JobId + ", Field Id:" + uploadedImg.FieldId + ", Image Name:" + uploadedImg.ImageName + ")]");

                    //Check whether to send email     

                    short? imageCount = job.ImageCount;

                    // log.Info("Ref No:" + refNo + ",ImageCount of Job:" + imageCount);

                    JobController jobCont = new JobController();

                    if (!isReSubmission && imageCount != null && job.ImageGalleries != null && (job.ImageGalleries.Count == imageCount))
                    {
                        // log.Info("Inside not is resubmission!");
                        //Send email            
                        try
                        {
                            jobCont.SendJobEmail(job, true);
                            log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + "Email sending started");
                            //  log.Info("Email send success for images.");
                        }
                        catch (Exception e)
                        {
                            log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image - Send Email," + User.Identity.Name + "," + e.Message);
                            // log.Info("Email send failure for images.");
                        }

                    }
                    else if (isReSubmission && refNo != 0)
                    {
                        // log.Info("Inside is resubmission!");
                        Job_ReSubmissions submission = (from s in slicImg.Job_ReSubmissions
                                                        where s.RefNo == refNo
                                                        select s).FirstOrDefault();

                        imageCount = submission.ImageCount;
                        //   log.Info("Ref No:" + refNo + ",ImageCount of Submission:" + imageCount);
                        if (submission != null)
                        {
                            //  log.Info("Submission Entity not null");
                            submission.ImageGalleries.Add(uploadedImg);
                            slicImg.SaveChanges();
                            // log.Info("Saved to link table on submission.");

                            if (imageCount != null && submission.ImageGalleries != null && (submission.ImageGalleries.Count == imageCount))
                            {
                                try
                                {
                                    jobCont.SendReSubmissionEmail(submission, true);
                                    log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + "Email sending started");
                                    // log.Info("Email send success for images on resubmission.");
                                }
                                catch (Exception e)
                                {
                                    log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image - Send Email," + User.Identity.Name + "," + e.Message);
                                    // log.Info("Email send failure for images on resubmission.");
                                }

                            }
                        }
                        else
                        {
                            //Submission entity not found for the image                           
                            throw new GenException(807, "Image ReSubmission entity not found.");
                        }
                    }
                    //logged on Success
                    log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image overall," + User.Identity.Name);
                }
            }
            catch (ArgumentException e)
            {
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + e.Message);
                ModelState.AddModelError("err", new GenException(710, "Error in handling ENUM"));
            }
            catch (GenException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + ex.Message);
                ModelState.AddModelError("err", ex);
            }
            catch (XmlException e)
            {
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + e.Message);
                ModelState.AddModelError("err", new GenException(711, "Error in xml data"));
            }
            catch (IOException e)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + e.Message);
                ModelState.AddModelError("err", new GenException(712, "File Path not Accessible"));
            }
            catch (SqlException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + ex.Message);
                ModelState.AddModelError("err", new GenException(713, "Error occurred while connecting to the database. Please try again later"));
            }
            catch (Exception e)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + e.Message);
                ModelState.AddModelError("err", new GenException(714, e.ToString()));
            }

            return GetFormatView("Image/ImageUpload.aspx");
        }

        private ImageGallery SaveImage(HttpPostedFileBase imageFile, string jobNo, string fieldName, bool isReSubmission, int refNo)
        {
            ImageGallery image = null;
            try
            {
                if (imageFile==null)
                {
                      throw new GenException(708, "Image not found.");
                }

                string commonFolderPath = "ImageGallery\\" + jobNo + "\\" + fieldName;

                if (isReSubmission && refNo != 0)
                {
                    commonFolderPath = "ImageGallery\\" + jobNo + "\\Visit_" + refNo + "\\" + fieldName;
                }
               
                string dateTimeStamp = String.Format("{0:MM_dd_yyyy_HH-mm-ss}", DateTime.Now);
                string newImageName = jobNo + "_" + dateTimeStamp + "_" + fieldName + "_" + Path.GetFileName(imageFile.FileName);

             string   dbImagepath = commonFolderPath + "\\" + newImageName;               
               
                FolderCreater.CreateFolder(ConfigurationManager.AppSettings["ImageSavePath"].ToString() + commonFolderPath);
              //  log.Info(LogPoint.Success.ToString() + ",Folders created at:" + filePath);

                string imageFullPath = ConfigurationManager.AppSettings["ImageSavePath"].ToString() + dbImagepath;

                if (System.IO.File.Exists(imageFullPath))
                {
                    throw new GenException(709, "Image Already exists");
                }

                imageFile.SaveAs(imageFullPath);

                //Create ImageEntity and return
                image = new ImageGallery();
                image.ImageName = newImageName;              
                image.ImagePath = dbImagepath;
                image.Title = newImageName;
                //logged on success of file upload 
                log.Info(LogPoint.FileUploaded.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + jobNo + User.Identity.Name + ",File Name:" + imageFullPath);
            }
            catch (Exception)
            {
                throw;
            } 
            return image;
        }

        ///GetImageArray Action Method        
        ///<returns>
        /// to RetrieveImageID
        ///</returns>       
        ///<exception cref="">        
        ///JobNo cant be empty
        ///Error occurred while connecting to the database.Please try again later
        /// </exception>
        /// <remarks>this method get the image ids as a list and send them as response</remarks>
        public virtual ActionResult GetImageArray(string jobNo)
        {
            //log.Info("this is a test log entry");        
            List<int> imageIDArray = new List<int>();
            try
            {
                log.Info(LogPoint.Entry.ToString() + "," + this.ControllerContext.Controller.ToString() + ",GetImageArray Started," + User.Identity.Name);
                using (SLICEntities slicImg = DataObjectFactory.CreateContext())
                {
                    if (string.IsNullOrEmpty(jobNo))
                    {
                        throw new GenException(621, "Job No cannot be null or empty");
                    }

                    imageIDArray = (from p in slicImg.ImageGalleries join d in slicImg.Jobs on p.JobId equals d.Id where d.JobNo == jobNo select p.ImageId).ToList();

                    if (imageIDArray.Count == 0)
                    {
                        throw new GenException(715, "No Images found for the job");
                    }
                    log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Retrieving Image ID overall," + User.Identity.Name);

                }

            }
            catch (ArgumentException e)
            {
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name);
                ModelState.AddModelError("err", new GenException(710, "Error in handling ENUM"));
            }
            catch (GenException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name);
                ModelState.AddModelError("err", ex);
            }
            catch (XmlException e)
            {
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name);
                ModelState.AddModelError("err", new GenException(711, "Error in xml data"));
            }
            catch (IOException e)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name);
                ModelState.AddModelError("err", new GenException(712, "File Path not Accessible"));
            }
            catch (EntityException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name + "," + ex.Message);
                ModelState.AddModelError("err", new GenException(713, "Error occurred while connecting to the database. Please try again later"));
            }
            catch (Exception e)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image," + User.Identity.Name);
                ModelState.AddModelError("err", new GenException(716, e.ToString()));
            }

            return GetFormatView("Image/RetrieveImageID.aspx", imageIDArray);
        }


        /*
        ///GetImageById Action Method        
        ///<returns>
        /// to Retrieve images
        ///</returns>       
        ///<exception cref="">        
        ///imageID cant be empty
        ///Error occurred while connecting to the database.Please try again later
        /// </exception>
        /// <remarks>this method get the image ids as a list and send them as response</remarks>
        public virtual ActionResult GetImageById(int imageID)
        {
            try
            {
                log.Info(LogPoint.Entry.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Image By Id," + User.Identity.Name + ",[Params=(Image Id:" + imageID + ")]");

                using (SLICEntities slicImg = DataObjectFactory.CreateContext())
                {
                    if (imageID == null || imageID == 0)
                    {
                        throw new GenException(717, "imageID can not be null");
                    }

                    ImageGallery imageEntity = (from g in slicImg.ImageGalleries
                                                where g.ImageId == imageID
                                                select g).FirstOrDefault();
                    if (imageEntity == null)
                    {
                        throw new GenException(718, "Image not found.");
                    }

                    
                    //int fieldID = (from p in slicImg.ImageGalleries where p.ImageId == imageID select p.FieldId).FirstOrDefault();
                    //string imagePath = (from p in slicImg.ImageGalleries where p.ImageId == imageID select p.ImagePath).FirstOrDefault();
                    

                    // if (string.IsNullOrEmpty(imagePath))
                    if (string.IsNullOrEmpty(imageEntity.ImagePath))
                    {
                        throw new GenException(718, "Image path not found");
                    }
                    //if (file1.ContentType != "application/pdf")
                    //{
                    //    throw new GenException(202, "Only .pdf files are allowed.");
                    //}

                    string filePath = ConfigurationManager.AppSettings["ImageSavePath"].ToString();
                    if (string.IsNullOrEmpty(filePath))
                    {
                        throw new GenException(719, "Error in Retrieving a path to Retrieve");
                    }
                    //Server.MapPath(filePath);

                    //filePath += imagePath;
                    filePath += imageEntity.ImagePath;

                    if (!System.IO.File.Exists(filePath))
                    {
                        throw new GenException(720, "Image does not exists");
                    }
                    // Response.Write("FieldId=" + fieldID);

                    Image oImg = Image.FromFile(filePath, true);
                    oImg.Save(Response.OutputStream, oImg.RawFormat);//ImageFormat.Jpeg); 

                    log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Image By Id," + User.Identity.Name + ",[Params=(Image Id:" + imageID + ")]");

                    //logged on Success
                    //log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Upload Image overall," + User.Identity.Name);
                }

            }
            catch (ArgumentException e)
            {
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Image By Id," + User.Identity.Name + "," + e.Message + ",[Params=(Image Id:" + imageID + ")]");
                ModelState.AddModelError("err", new GenException(710, "Error in handling ENUM"));
            }
            catch (GenException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Image By Id," + User.Identity.Name + "," + ex.Message + ",[Params=(Image Id:" + imageID + ")]");
                ModelState.AddModelError("err", ex);
            }
            catch (XmlException e)
            {
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Image By Id," + User.Identity.Name + "," + e.Message + ",[Params=(Image Id:" + imageID + ")]");
                ModelState.AddModelError("err", new GenException(711, "Error in xml data"));
            }
            catch (IOException e)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Image By Id," + User.Identity.Name + "," + e.Message + ",[Params=(Image Id:" + imageID + ")]");
                ModelState.AddModelError("err", new GenException(712, "File Path not Accessible"));
            }
            catch (EntityException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Image By Id," + User.Identity.Name + "," + ex.Message + ",[Params=(Image Id:" + imageID + ")]");
                ModelState.AddModelError("err", new GenException(713, "Error occured while connecting to the database.Please try again later"));
            }
            catch (Exception e)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Image By Id," + User.Identity.Name + "," + e.Message + ",[Params=(Image Id:" + imageID + ")]");
                ModelState.AddModelError("err", new GenException(721, e.ToString()));
            }

            // return null;
            return GetFormatView("Image/ImageUpload.aspx");
        }
        */

        ///GetImageById Action Method        
        ///<returns>
        /// to Retrieve images
        ///</returns>       
        ///<exception cref="">        
        ///imageID cant be empty
        ///Error occurred while connecting to the database.Please try again later
        /// </exception>
        /// <remarks>this method get the image ids as a list and send them as response</remarks>
        public virtual ActionResult GetImageById(int imageID)
        {
            try
            {
                log.Info(LogPoint.Entry.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Image By Id," + User.Identity.Name + ",[Params=(Image Id:" + imageID + ", User Agent:" + Request.UserAgent + ")]");

                using (SLICEntities slicImg = DataObjectFactory.CreateContext())
                {
                    if (imageID == null || imageID == 0)
                    {
                        throw new GenException(717, "imageID can not be null");
                    }

                    ImageGallery imageEntity = (from g in slicImg.ImageGalleries
                                                where g.ImageId == imageID
                                                select g).FirstOrDefault();
                    if (imageEntity == null)
                    {
                        throw new GenException(718, "Image not found.");
                    }

                    if (string.IsNullOrEmpty(imageEntity.ImagePath))
                    {
                        throw new GenException(718, "Image path not found");
                    }

                    string filePath = ConfigurationManager.AppSettings["ImageSavePath"].ToString();
                    if (string.IsNullOrEmpty(filePath))
                    {
                        throw new GenException(719, "Error in getting image path from config.");
                    }

                    filePath += imageEntity.ImagePath;

                    if (!System.IO.File.Exists(filePath))
                    {
                        throw new GenException(720, "Image does not exists");
                    }

                    Image oImg = Image.FromFile(filePath, true);
                    oImg.Save(Response.OutputStream, oImg.RawFormat);
                    log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Image By Id," + User.Identity.Name + ",[Params=(Image Id:" + imageID + ", User Agent:" + Request.UserAgent + ")]");
                }
            }
            catch (ArgumentException e)
            {
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Image By Id," + User.Identity.Name + "," + e.Message + ",[Params=(Image Id:" + imageID + ")]");
                ModelState.AddModelError("err", new GenException(710, "Error in handling ENUM"));
            }
            catch (GenException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Image By Id," + User.Identity.Name + "," + ex.Message + ",[Params=(Image Id:" + imageID + ")]");
                ModelState.AddModelError("err", ex);
            }
            catch (IOException e)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Image By Id," + User.Identity.Name + "," + e.Message + ",[Params=(Image Id:" + imageID + ")]");
                ModelState.AddModelError("err", new GenException(712, "File Path not Accessible"));
            }
            catch (SqlException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Image By Id," + User.Identity.Name + "," + ex.Message + ",[Params=(Image Id:" + imageID + ")]");
                ModelState.AddModelError("err", new GenException(713, "Error occurred while connecting to the database.Please try again later"));
            }
            catch (Exception e)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",Get Image By Id," + User.Identity.Name + "," + e.Message + ",[Params=(Image Id:" + imageID + ")]");
                ModelState.AddModelError("err", new GenException(721, e.ToString()));
            }

            // return null;
            return GetFormatView("Image/ImageUpload.aspx");
        }



        #endregion

        #region html action

        /// <summary>show all images in image gallery view</summary>        
        ///<param name="JobId">JobId</param>        
        ///<returns>
        ///Returns the status of the action
        ///</returns>
        ///<exception cref="">
        ///XML incorrect format
        ///job number exists
        ///database errors
        /// </exception>        
        /// <remarks></remarks>
        public virtual ActionResult ViewImageGallery(int JobId)
        {
            List<ImageGallery> imageGallery;
            try
            {
                //logged on entry
                log.Info(LogPoint.Entry.ToString() + "," + this.ControllerContext.Controller.ToString() + ",View Image Gallery," + User.Identity.Name);

                if (JobId == null)
                {
                    throw new GenException(720, "JobId cant be null");
                }
                using (SLICEntities slic = DataObjectFactory.CreateContext())
                {
                    imageGallery = (from d in slic.ImageGalleries
                                    where d.JobId == JobId && (d.IsReSubmission == null || d.IsReSubmission == false)
                                    select d).ToList();
                    imageGallery = this.SetImageCaption(imageGallery);

                    //can pass this through url parameters - do be done on clean up
                    ViewData["JobNo"] = (from j in slic.Jobs
                                         where j.Id == JobId
                                         select j.JobNo).FirstOrDefault();

                    if (imageGallery.Count == 0)
                    {
                        throw new GenException(721, "No images available.");
                    }

                    //Generate Thump image
                    //try
                    //{
                    //    ImageUtilities imgUtility = new ImageUtilities();
                    //    string originalPath = ConfigurationManager.AppSettings["ImageSavePath"].ToString();
                    //    string thumbPath = ConfigurationManager.AppSettings["ThumbPath"].ToString();
                    //    foreach (ImageGallery p in imageGallery)
                    //    {

                    //        Bitmap b = new Bitmap(originalPath + p.ImagePath);
                    //        Image i = imgUtility.resizeImage(b, new Size(72, 72));

                    //        b.Dispose();
                    //        string thumb = Path.GetDirectoryName(thumbPath + p.ImagePath); ;
                    //        StaticMethods.CreateFolder(thumb);
                    //        imgUtility.saveJpeg(thumbPath + p.ImagePath, (Bitmap)i, 100);
                    //    }

                    //}
                    //catch (Exception e)
                    //{
                    //    log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",View Image Gallery," + User.Identity.Name + "," + e.Message);
                    //}

                    //logged on success
                    log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",View Image Gallery," + User.Identity.Name);
                    return GetFormatView("Image/ViewImageGallery.aspx", imageGallery);
                }
            }

            catch (GenException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",View Image Gallery," + User.Identity.Name);
                ModelState.AddModelError("err", ex);
            }
            catch (SqlException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",View Image Gallery," + User.Identity.Name + "," + ex.Message);
                ModelState.AddModelError("err", new GenException(721, "Error occurred while connecting to the database.Please try again later"));
            }
            catch (Exception e)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",View Image Gallery," + User.Identity.Name);
                ModelState.AddModelError("err", new GenException(722, e.ToString()));
            }
            return GetFormatView("Image/ViewImageGallery.aspx");
        }


        /// <summary>show all Revisit images in image gallery view</summary>        
        ///<param name="submissionId">Resubmission ID</param>        
        ///<returns>
        ///Returns the status of the action
        ///</returns>
        ///<exception cref="">
        ///XML incorrect format
        ///job number exists
        ///database errors
        /// </exception>        
        /// <remarks></remarks>
        

        public virtual ActionResult ViewVisitGallery(int? submissionId)
        {
            List<ImageGallery> imageGallery;

            try
            {
                //logged on entry 
                log.Info(LogPoint.Entry.ToString() + "," + this.ControllerContext.Controller.ToString() + ",View Image Gallery," + User.Identity.Name);

                if (submissionId == null)
                {
                    throw new GenException(720, "Please select a visit");
                }

                using (SLICEntities slic = DataObjectFactory.CreateContext())
                {
                    Job_ReSubmissions submissionEntity = (from s in slic.Job_ReSubmissions
                                                          where s.ReSubmissionId == (int)submissionId
                                                          select s).FirstOrDefault();

                    ViewData["JobNo"] = submissionEntity.Job.JobNo;
                    ViewData["SubmissionId"] = submissionId;
                    ViewData["ReSubmission"] = true;

                    imageGallery = submissionEntity.ImageGalleries.ToList();
                    imageGallery = this.SetImageCaption(imageGallery);

                    if (imageGallery.Count == 0)
                    {
                        throw new GenException(721, "No images available.");
                    }

                    log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",View Image Gallery," + User.Identity.Name);
                    return GetFormatView("Image/ViewImageGallery.aspx", imageGallery);
                }
            }
            catch (GenException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",View Image Gallery," + User.Identity.Name);
                ModelState.AddModelError("err", ex);
            }
            catch (SqlException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",View Image Gallery," + User.Identity.Name + "," + ex.Message);
                ModelState.AddModelError("err", new GenException(721, "Error occurred while connecting to the database. Please try again later"));
            }
            catch (Exception e)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",View Image Gallery," + User.Identity.Name);
                ModelState.AddModelError("err", new GenException(722, e.ToString()));
            }

            return GetFormatView("Image/ViewImageGallery.aspx");
        }

        /// <summary>Print Image by image Number </summary>        
        ///<param name="ImageNumber">Image Number</param>        
        ///<returns>
        ///Returns the status of the action
        ///</returns>
        ///<exception cref="">
        ///XML incorrect format
        ///job number exists
        ///database errors
        /// </exception>        
        /// <remarks></remarks>


        public virtual ActionResult ImagePrinted(int? ImageNumber)
        {
            //ImageGallery image;
            try
            {
                //logged on entry
                log.Info(LogPoint.Entry.ToString() + "," + this.ControllerContext.Controller.ToString() + ",ImagePrinted," + User.Identity.Name);

                if (ImageNumber == null)
                {
                    throw new GenException(720, "Image Number can't be null or empty");
                }
                using (SLICEntities entities = DataObjectFactory.CreateContext())
                {
                    ImageGallery image = (from d in entities.ImageGalleries
                                          where d.ImageId == ImageNumber
                                          select d).FirstOrDefault();
                    if (image == null)
                    {
                        throw new GenException(720, "Image not found.");
                    }
                    image.IsPrinted = true;
                    entities.SaveChanges();

                    // ViewData["JobNo"] = "Sample";

                    log.Info(LogPoint.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",ImagePrinted," + User.Identity.Name);
                    return GetFormatView("Image/PrintImage.aspx");
                }
            }
            catch (GenException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",ImagePrinted," + User.Identity.Name);
                ModelState.AddModelError("err", ex);
            }
            catch (SqlException ex)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",ImagePrinted," + User.Identity.Name + "," + ex.Message);
                ModelState.AddModelError("err", new GenException(721, "Error occurred while connecting to the database. Please try again later"));
            }
            catch (Exception e)
            {
                //logged on exception
                log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",ImagePrinted," + User.Identity.Name);
                ModelState.AddModelError("err", new GenException(722, e.ToString()));
            }
            return GetFormatView("Image/PrintImage.aspx");
        }

        #endregion

        #region privateMethods


        /// <summary>Set Image Caption in View </summary>        
        ///<param name="ImageGalleryr">List of Images</param>        
        ///<returns>
        ///Image Gallery List
        ///</returns>
        ///<exception cref="">
        /// </exception>        
        /// <remarks></remarks>

        private List<ImageGallery> SetImageCaption(List<ImageGallery> imageGallery)
        {
            foreach (ImageGallery image in imageGallery)
            {
                string printedFlag = string.Empty;

                if (image.IsPrinted == null || !(bool)image.IsPrinted)
                {
                    printedFlag = "Original";
                }
                else
                {
                    printedFlag = "Copy";
                }
                image.LightBoxCaption = image.ImageId.ToString() + " | " + printedFlag + " | " + image.Title;
            }
            return imageGallery;
        }

        #endregion privateMethods

    }
    public static class FolderCreater
    {
        /// <summary>Create Folder</summary>        
        ///<param name="path">Path of the Folder</param>        
        ///<returns>
        ///</returns>
        ///<exception cref="">
        /// </exception>        
        /// <remarks></remarks>
        [NonAction]
        public static void CreateFolder(string path)
        {
            if (!Directory.GetParent(path).Exists)
            {
                CreateFolder(Directory.GetParent(path).FullName);
            }
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
        }
    }
}
